# -*- coding: UTF-8 -*-
import os
import shutil
import subprocess
import sys


def clearzj(path):
    files = os.listdir(path)
    for fd in files:
        cur_path = os.path.join(path, fd)
        if os.path.isdir(cur_path):
            if fd == '__pycache__' or fd == 'build':
                shutil.rmtree(cur_path)
            else:
                clearzj(cur_path)
        else:
            _, ext = os.path.splitext(cur_path)
            if ext == '.c' or ext == '.py':
                if '__init__' not in cur_path:
                    os.remove(cur_path)


# 获取文件夹下所有的.py文件, 文件夹可以是多层级的
def find_py_files(folder):
    py_files = []
    for item in os.listdir(folder):
        item_path = os.path.join(folder, item)
        if os.path.isfile(item_path):
            if item.endswith('.py'):
                py_files.append(item_path)
        elif os.path.isdir(item_path):
            py_files.extend(find_py_files(item_path))
    return py_files


def pack_cython(src_path, dest_path):
    # 1. 将需要打包的整个源目录整个复制出来，形成目标目录
    if os.path.exists(dest_path):
        shutil.rmtree(dest_path)
    if os.path.exists(src_path):
        shutil.copytree(src_path, dest_path)
    if os.path.exists(dest_path) is False:
        print(f'目标文件夹={dest_path}不存在!')
        return
    # 2. 除了__init__.py外，编译其他的 .py文件
    py_files = find_py_files(dest_path)
    for py in py_files:
        if '__init__' not in py:
            cmd = ['cythonize', '-i', py]
            try:
                subprocess.run(cmd, check=True)
            except subprocess.CalledProcessError as e:
                print('Cython编译失败:', e)
                sys.exit(0)
    # 3. 清理掉所有的中间文件以及除了__init__.py外的.py源码文件
    clearzj(dest_path)
    # 4. 将目标文件夹改名成源文件夹就可以使用了


if __name__ == '__main__':
    src_folder = './cython_module_2'
    dest_folder = f'{src_folder}_back'
    pack_cython(src_folder, dest_folder)
